// import { fetchPermission } from "../../api/index"
// import router, { DynamicRoutes } from "../../router/index"
// //DynamicRoutes是初始化的路由，准备根据权限添加
// import dynamicRouter from "../../router/dynamic-router"
//dynamicRouter全部路由组  根据后端返回的做筛选的
import { recursionRouter, setDefaultRoute } from "@/utils/recursion-router"
import { defineStore } from 'pinia'

export const useRoutesStore=defineStore(
    'permission-routes',
    ()=> {
    let permissionList=null
    let sidebarMenu= []// 导航菜单
    let currentMenu= '' // 高亮

    const SET_PERMISSION = ( routes)=> {
        permissionList = routes
    }
    const CLEAR_PERMSSION = ()=> {
        permissionList = null
    }
    const SET_MENU = ( menu)=> {
        sidebarMenu = menu
    }
    const CLEAR_MENU = ()=> {
        sidebarMenu = []
    }

    const FETCH_PERMISSION = async ()=> {
        // 获取权限(admin/commmon_user)
        let permissionList = await fetchPermission();
        // permissionList 是权限JSON

        // 筛选
        //  permissionList 是权限JSON   dynamicRouter总路由组
        let routes = recursionRouter(permissionList, dynamicRouter);
        // 符合条件的路由添加到DynamicRoutes
        let MainContainer = DynamicRoutes.find(v => v.path === "");
        // 如果为空就把MainContainer添加成子元素
        let children = MainContainer.children;
        children.push(...routes)

        // 生成菜单
        // commit("SET_MENU", children);
        SET_MENU(children)
        // 设置默认路由
        setDefaultRoute([MainContainer]);
        // 初始化路由
        let initialRoutes = router.options.routes;
        router.addRoutes(DynamicRoutes);

        // commit("SET_PERMISSION", [...initialRoutes, ...DynamicRoutes])
        SET_PERMISSION([...initialRoutes, ...DynamicRoutes])
    }

    return{
        permissionList,
        sidebarMenu,
        currentMenu,
        SET_PERMISSION,
        CLEAR_PERMSSION,
        SET_MENU,
        CLEAR_MENU,
        FETCH_PERMISSION
    }
},
{
    persist: true
}
)
